package lrscp.lib.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URL;

import lrscp.lib.io.Monitor.ProgressMonitor;

import org.apache.commons.io.IOUtils;

public class MIOutils {
    public static String readLine(InputStream in) {
        try {
            return new BufferedReader(new InputStreamReader(in)).readLine();
        } catch (IOException e) {
            return null;
        }
    }

    public static long copy(InputStream input, OutputStream output, ProgressMonitor monitor)
            throws IOException {
        byte[] buffer = new byte[4096];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
            monitor.addProgress(n);
        }
        return count;
    }

    public static String getHtml(String typeUrl, String encoding) {
        StringWriter sw = new StringWriter();
        try {
            URL url = new URL(typeUrl);
            IOUtils.copy(new URL(typeUrl).openStream(), sw, encoding);
        } catch (IOException e) {
            sw.append(e.getMessage());
            e.printStackTrace();
        }
        return sw.toString();
    }
}
